package actions;

import java.awt.event.ActionEvent;

import client.ClientApplication;
import client.ClientBindObject;
import client.ClientSocketConnection;
import client_gui.ClientWindow;
import client_tree.User;

public class DeleteUserAction extends RLMAbstractAction {

	public DeleteUserAction(ClientWindow owner) {
		setActionOwner(owner);
//		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
		putValue(SMALL_ICON, loadIcon("images/delete.png"));
		putValue(NAME, "Delete User");
		putValue(SHORT_DESCRIPTION, "Brisanje korisnika");
	}
	
	
	public void actionPerformed(ActionEvent e) {
		
		ClientSocketConnection connection = getActionOwner().getApplicaton().retrieveSocketConnection();
		
		User user = getActionOwner().getSelectedUser();
		
		getActionOwner().getApplicaton().getClientModel().removeUser(user);
		
		StringBuffer deleteCommand = new StringBuffer();
		
		deleteCommand.append("DEL ");
		deleteCommand.append(getActionOwner().getApplicaton().getClientUser().getUsername());
		deleteCommand.append(" ");
		deleteCommand.append(user.getUsername());
		
		String deleteCommandCompleted = deleteCommand.toString();

		connection.setMessage(DEL_CMD, deleteCommandCompleted);
		
		String response = connection.buffers[DEL_CMD].read();
		
		if (response.startsWith("100")) {
			if ( !getActionOwner().getApplicaton().getClientUser().isBlocked(user.getUsername()) ) {
				getActionOwner().getApplicaton().getClientUser().addToBlockList(user.getUsername());
			}
			getActionOwner().refreshTree();
			
			ClientBindObject cbo = ClientApplication.clientBinding.remove(user.getUsername());
			if (cbo != null) {
				if (cbo.getDialog() != null) {
					cbo.getDialog().setConnection(null);
					cbo.getDialog().dispose();
				}
				cbo.getConnection().quitConnection();
				cbo.setConnection(null);
			}
		}
	}
	
}
